package schoolword;

import java.util.Scanner;

public class Text4 {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.print("请输入一个邮箱: ");
            String email = scanner.next();

            if (checkEmail(email)) {
                String domain = getDomain(email);
                System.out.println("该邮箱地址的域名: " + domain);
                break;
            } else {
                System.out.println("请重新输入");
            }
        }
    }

    public static boolean checkEmail(String s) {
        if (!s.contains("@")) {
            return false;
        }
        if(countStr(s,"@") > 1) {
            return false;
        }
        if(countStr(s,".") > 1) {
            return false;
        }

        int atIndex = s.indexOf("@");
        if (atIndex == 0 || atIndex == s.length() - 1) {
            return false;
        }

        String afterAt = s.substring(atIndex + 1);
        if (!afterAt.contains(".")) {
            return false;
        }

        int dotIndex = afterAt.indexOf(".");
        if (dotIndex == 0 || dotIndex == afterAt.length() - 1) {
            return false;
        }

        String beforeAt = s.substring(0, atIndex);
        if (beforeAt.length() < 3) {
            return false;
        }

        String[] endings = {".com", ".org", ".cn", ".net"};
        boolean isEnd = false;
        for (String ending : endings) {
            if (s.endsWith(ending)) {
                isEnd = true;
                break;
            }
        }
        return isEnd;
    }

    //获取域名
    public static String getDomain(String email) {
        int atIndex = email.indexOf("@");
        return email.substring(atIndex + 1);
    }

    //获取子串在字符串中的个数
    public static int countStr(String str , String subStr) {
        int count = 0;
        int index = str.indexOf(subStr);
        while (index != -1) {
            count++;
            index = str.indexOf(subStr,index+1);
        }
        return count;
    }
}
